<?php

namespace IDock\Insurance\LIHI;

use IDock\Common\BaseInterface\BuilderInterface;
use IDock\Http\Request;
use IDock\Http\Response;
use IDock\Insurance\LIHI\Request\AllLIHIRequest;
use IDock\Insurance\LIHI\Response\AllLIHIResponse;

class Builder implements BuilderInterface
{

    public function getConfig(): array
    {
        return $this->config;
    }

    protected $config;

    protected $partnerAccountCode;

    protected $recordCode;

    protected $agreementNo;

    protected $tokenUrl;

    public $token;

    public $notifyUrl;

    public function execute(Request $request): Response
    {
        /*** @var AllLIHIRequest $request */
        $request->loadConfig($this->config);

        $request->setRequestId(md5(uniqid()));
        $data = $this->generate($request);
        $request->setHeaders(['Content-Type' => 'application/json']);
        $publicParam = [
            'partnerAccountCode' => $this->partnerAccountCode,
            'flowId' => $request->flowId ?: $this->partnerAccountCode.date('ymd').mt_rand(10000000,99999999),
            'recordCode' => $this->recordCode,//备案号
            'agreementNo' => $this->agreementNo,
            'operatorDate' => date('Y-m-d H:i:s'),
        ];
        $data = array_merge($publicParam,$data);
        $this->specialRequest($request,$data);
        $request->setPreParameter($data);
        $request->setBizParam($data);
        return $this->request($request);
    }

    private function specialRequest(AllLIHIRequest $request,&$data)
    {
        $isJson = 1;
        if($request->route == 'oauth/token'){
            $request->setGateway($this->tokenUrl);
            $request->route = '';
            $data = '';
        }elseif($request->route == 'cp/upload/queryDocType/'){
            $request->route .= ($data['biInquiryNo'] ?: $data['ciInquiryNo']).'?access_token='.$this->token;
            unset($data['biInquiryNo']);
            unset($data['ciInquiryNo']);
        }elseif($request->route == 'zuul/cp/upload/uploadDocument'){
            $data = $this->generate($request);
            $data[] = ['name'=>'partnerAccountCode','contents'=> $this->partnerAccountCode];
            $data[] = ['name'=>'flowId','contents'=> $request->flowId ?: $this->partnerAccountCode.date('ymd').mt_rand(10000000,99999999)];
            $data[] = ['name'=>'recordCode','contents'=> $this->recordCode];
            $data[] = ['name'=>'agreementNo','contents'=> $this->agreementNo];
            $data[] = ['name'=>'operatorDate','contents'=> date('Y-m-d H:i:s')];
            $request->route .= '?access_token='.$this->token;
            $request->setHeaders([]);
            $isJson = 0;
        }elseif ($request->route == 'calculate/combinecalculate'){
            if(isset($data['tprpTmainDto']['callBackUrl'])){
                $data['tprpTmainDto']['callBackUrl'] = $this->notifyUrl;
            }
            $request->route .= '?access_token='.$this->token;
        }elseif ($request->route == 'payment/getPayUrl'){
            if(isset($data['callBackUrl'])){
                $data['callBackUrl'] = $this->notifyUrl;
            }
            $request->setHeaders([]);
            $request->route .= '?access_token='.$this->token;
            $isJson = 0;
        }elseif ($request->route == 'cpservice/savePlan'){
            $data['motorProposalNo'] = $request->proposalNo;
            $request->route .= '?access_token='.$this->token;
        }else{
            $request->route .= '?access_token='.$this->token;
        }
        if($isJson){
            $data = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        }
    }

    public function generate(Request $request): array
    {
        return $request->generate();
    }

    public function sign(Request $request): Request
    {
        return $request;
    }

    public function exceptionResponse($request, $errorMessage): Response
    {
        $response = $request->getResponse();

        $response = new $response;
        $response->setCode('500');
        $response->setError($errorMessage);

        return $response;
    }

    public function request(Request $request): Response
    {
        /*** @var AllLIHIResponse $response */
        $response = $request->request($request);
        $response->setVisitor($request->getVisitor());

        if ($response->isSuccess()) {
            $response->printerInit();
        }
        return $response;
    }

    public function encrypt(Request $request)
    {

    }

    public function setToken($token)
    {
        $this->token = $token;
    }
}


